package com.example.goodsmanagementcabinet.speaker;

import android.speech.tts.TextToSpeech;
import android.widget.Toast;

import com.example.goodsmanagementcabinet.base.GoodBoxManagerApp_;

import org.androidannotations.annotations.EBean;

import java.util.Locale;

@EBean(scope = EBean.Scope.Singleton)
public class Speaker implements TextToSpeech.OnInitListener {
    public static boolean sIsSupportSpeak = true;
    private TextToSpeech tts;
    public void init(){
        tts = new TextToSpeech(GoodBoxManagerApp_.getInstance(),this);
    }

    @Override
    public void onInit(int status) {
        // TTS is successfully initialized
        if (status == TextToSpeech.SUCCESS) {
            // Setting speech language
            int result = tts.setLanguage(Locale.CHINA);
            // If your device doesn't support language you set above
            if (result == TextToSpeech.LANG_MISSING_DATA
                    || result == TextToSpeech.LANG_NOT_SUPPORTED) {
                // Cook simple toast message with message
                sIsSupportSpeak = false;
                Toast.makeText(GoodBoxManagerApp_.getInstance(), "Speak Language not supported",
                        Toast.LENGTH_LONG).show();
            } else {
                sIsSupportSpeak = true;
            }
        } else {
            Toast.makeText(GoodBoxManagerApp_.getInstance(), "Speak Language not supported",
                    Toast.LENGTH_LONG).show();
            sIsSupportSpeak = false;
        }
    }

    public void speak(String text) {
        if (text.length() == 0) {
            tts.speak("You haven't typed text", TextToSpeech.QUEUE_FLUSH, null);
        } else {
            if(tts.isSpeaking()) {
                tts.stop();
            }
            tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);

        }

    }

    public void stop(){
        if(tts.isSpeaking()) {
            tts.stop();
        }
    }
}
